package com.wesley.netty.quickstart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * NettyByteBuf
 *
 * @author WangPanYong
 * @since 2021/11/13 18:42
 */
public class NettyByteBuf {

    public static void main(String[] args) {
        // 创建byteBuf对象，该对象内部包含一个字节数组byte[10]
        ByteBuf buffer = Unpooled.buffer(10);
        System.out.println("byteBuf=" + buffer);

        // writerIndex 移动到 8
        for (int i = 0; i < 8; i++) {
            buffer.writeByte(i);
        }
        System.out.println("byteBuf=" + buffer);

        for (int i = 0; i < 5; i++) {
            System.out.println(buffer.getByte(i));
        }
        System.out.println("byteBuf=" + buffer);

        // readIndex 移动到 5
        for (int i = 0; i < 5; i++) {
            System.out.println(buffer.readByte());
        }
        System.out.println("byteBuf=" + buffer);

        //用Unpooled工具类创建ByteBuf
        ByteBuf byteBuf2 = Unpooled.copiedBuffer("hello,zhuge!", CharsetUtil.UTF_8);
        if (byteBuf2.hasArray()) {
            byte[] content = byteBuf2.array();
            //将 content 转成字符串
            System.out.println(new String(content, CharsetUtil.UTF_8));
            System.out.println("byteBuf2=" + byteBuf2);

            // 获取数组0这个位置的字符h的ascii码，h=104
            System.out.println(byteBuf2.getByte(0));

            int len = byteBuf2.readableBytes();
            System.out.println("len=" + len);

            //使用for取出各个字节
            for (int i = 0; i < len; i++) {
                System.out.println((char) byteBuf2.getByte(i));
            }

            //范围读取
            System.out.println(byteBuf2.getCharSequence(0, 6, CharsetUtil.UTF_8));
            System.out.println(byteBuf2.getCharSequence(6, 6, CharsetUtil.UTF_8));
        }

    }
}
